﻿using Microsoft.AspNetCore.Authorization;
using PMRC.API.Context;
using PMRC.API.Domain;
using System.Linq;
using System.Security.Claims;

namespace PMRC.API.Authorization
{
    /// <summary>
	/// 
	/// </summary>
	public class AuthorizationRequirement : IAuthorizationRequirement
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="permissionName"></param>
        public AuthorizationRequirement(string permissionName)
        {
            PermissionName = permissionName;
        }
        /// <summary>
        /// 权限名称
        /// </summary>
        public string PermissionName { get; }
    }

    /// <summary>
    /// 权限处理
    /// </summary>
    public class PermissionHandler : AuthorizationHandler<AuthorizationRequirement>
    {
        private readonly DbContext _db;

        public PermissionHandler(DbContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 权限校验
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationRequirement requirement)
        {
            var user = context.User;
            if (user != null && user.Identity != null && user.Identity.IsAuthenticated)
            {
                var userIdStr = user.FindFirstValue(ClaimTypes.NameIdentifier);
                if (!string.IsNullOrEmpty(userIdStr))
                {
                    var userId = Guid.Parse(userIdStr);
                    var roleIds = await _db.Queryable<SysUserRole>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
                    var permissionIds = await _db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId)).Select(x => x.PermissionId).ToListAsync();
                    var permissionNames = await _db.Queryable<SysPermission>().Where(x => permissionIds.Contains(x.Id)).Select(x => x.Name).ToListAsync();
                    if (permissionNames.Contains(requirement.PermissionName))
                    {
                        //通过验证
                        context.Succeed(requirement);
                    }
                }

            }
            await Task.CompletedTask;
        }
    }

}
